package lumis.service.pagepersonalization.doui.processactionhandler;

import java.util.Collection;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.doui.source.field.ISourceField;
import lumis.portal.PortalException;
import lumis.portal.UnexpectedException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.preferences.IPreferences;
import lumis.portal.serviceinterfaceinstance.ServiceInterfaceInstanceConfig;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.service.pagepersonalization.PagePersonalizationUtil;

/**
 * {@link ProcessActionHandler} responsible for reseting user page back to
 * default configuration.
 *
 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
public class ResetPageProcessActionHandler extends ProcessActionHandler<Source<ISourceField>>
{
	private static final String HOLDER_SERVICE_INTERFACE_ID = "lumis.service.pagepersonalization.widgetHolder";

	public void processAction() throws PortalException
	{
		String pageId = douiContext.getRequest().getPageConfig().getId();
		Collection<String> interfaceInstanceIds = ManagerFactory.getServiceInterfaceInstanceManager().getIdsByPageId(sessionConfig, pageId,
				transaction);
		for (String interfaceInstaceId : interfaceInstanceIds)
		{
			ServiceInterfaceInstanceConfig serviceInterfaceInstanceConfig = ManagerFactory.getServiceInterfaceInstanceManager().get(
					SessionConfig.getCurrentSessionConfig(), interfaceInstaceId, PortalTransactionFactory.getCurrentTransaction());
			if (serviceInterfaceInstanceConfig.getServiceInterfaceId().equals(
					HOLDER_SERVICE_INTERFACE_ID))
			{
				IPreferences preferences = ManagerFactory.getPreferencesManager().getPreferences(sessionConfig, interfaceInstaceId,
						IPreferences.TYPE_SERVICE_INTERFACE_INSTANCE);
				try
				{
					preferences.reset(PagePersonalizationUtil.WIDGETS_PREFERENCES_NAME);
					preferences.store();
				}
				catch (Exception e)
				{
					throw new UnexpectedException(e);
				}
			}
		}
		addDefaultResponse();
	}
}
